package com.xkdx.guangguang.card;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;

import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.xkdx.caipiao.R;
import com.xkdx.guangguang.CardActivity;
import com.xkdx.guangguang.ManagerActivity;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.module.statics.IConstants;
import com.xkdx.guangguang.util.SharePrefenceUtil;

public class CardInfoFragment extends BaseFragment {

	View view;
	CardInfoAction action;
	CardInfoModule module;
	CardInfoPresistence presistence;
	PopupWindow popupWindow, popupWindow2;
	String BankID = "", Con1 = "", Con2 = "distance", Con1Value = "";
	public static String BANKID = "BankID", CON1 = "con1", CON2 = "Con2",
			CON1VALUE = "con1Value", ISBRANCH = "isBranch";
	ListView ls_card;
	TextView tv1, tv2;
	ImageView tv1PullDown, tv2PullDown;
	List<CardInfo> list;
	String[] con2s = { "distance", "", "low" };
	DisplayImageOptions options;
	RelativeLayout default_im;
	ImageLoader imageLoader = ImageLoader.getInstance();
	LinearLayout ll, card_ly1;
	RelativeLayout rl;
	ImageView back;
	DisplayMetrics metrics;
	int Rl, ll_height, rl_height;
	boolean isShop = false;
	boolean isBrand = false;
	String[] Strs;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		final RelativeLayout rl = ((ManagerActivity) getActivity()).mRl;

		ViewTreeObserver vto2 = rl.getViewTreeObserver();
		vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			@Override
			public void onGlobalLayout() {
				rl.getViewTreeObserver().removeGlobalOnLayoutListener(this);
				Rl = rl.getHeight();
			}
		});

		metrics = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay()
				.getMetrics(metrics);

		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.focuse_brand_discount)
				.showImageForEmptyUri(R.drawable.focuse_brand_discount)
				.showImageOnFail(R.drawable.focuse_brand_discount)
				.resetViewBeforeLoading().cacheOnDisc()
				.imageScaleType(ImageScaleType.EXACTLY)
				.bitmapConfig(Bitmap.Config.RGB_565).build();

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.card, container, false);
		findView();
		getCard("", Con2);
		setOnClick();
		// TODO Auto-generated method stub
		return view;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

	}

	private void getCard(String BankID, String Con2) {
		this.BankID = BankID;
		this.Con2 = Con2;
		SharePrefenceUtil su = new SharePrefenceUtil(getActivity(),
				IConstants.SP_CITY);
		String cityID = su.getCityID();
		action = new CardInfoAction(BankID, Con1, Con2, Con1Value,
				String.valueOf(IConstants.lat), String.valueOf(IConstants.lon),
				"1", "1000", cityID);
		module = new CardInfoModule();
		presistence = new CardInfoPresistence(this);
		presistence.setActitons(action);
		presistence.setModule(module);
		presistence.execute();
		dataLoadDialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				if (presistence != null) {
					presistence.cancel(true);
				}
				getActivity().finish();
			}
		});
		if (getActivity() != null) {
			dataLoadDialog.show();
		}

	}

	@Override
	public void findView() {
		ls_card = (ListView) view.findViewById(R.id.lv_card);
		tv1 = (TextView) view.findViewById(R.id.tv1);
		tv2 = (TextView) view.findViewById(R.id.tv2);
		tv1PullDown = (ImageView) view.findViewById(R.id.tv1_pull_down);
		tv2PullDown = (ImageView) view.findViewById(R.id.tv2_pull_down);
		card_ly1 = (LinearLayout) view.findViewById(R.id.card_ly1);
		back = (ImageView) view.findViewById(R.id.back_card_info);
		default_im = (RelativeLayout) view.findViewById(R.id.defalt_rl);
		ll = (LinearLayout) view.findViewById(R.id.ll);
		rl = (RelativeLayout) view.findViewById(R.id.tableRow1);

		ViewTreeObserver vto2 = ll.getViewTreeObserver();
		vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			@Override
			public void onGlobalLayout() {
				ll.getViewTreeObserver().removeGlobalOnLayoutListener(this);
				ll_height = ll.getHeight();
			}
		});
		ViewTreeObserver vto1 = rl.getViewTreeObserver();
		vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			@Override
			public void onGlobalLayout() {
				rl.getViewTreeObserver().removeGlobalOnLayoutListener(this);
				rl_height = rl.getHeight();
			}
		});

		if (getArguments() != null) {
			back.setVisibility(View.VISIBLE);
			Bundle b = getArguments();
			if (b.getString(BANKID) != null) {
				BankID = b.getString(BANKID);
			}
			if (b.getString(CON1) != null) {
				Con1 = b.getString(CON1);
				if (Con1.equals("shop")) {
					isShop = true;
					tv2.setText(getString(R.string.card_new));
				}
				if (Con1.equals("brand")) {
					isBrand = true;
					tv2.setText(getString(R.string.card_near));
				}
			}
			if (b.getString(CON2) != null) {
				Con2 = b.getString(CON2);
				if (isShop) {
					Con2 = "";
				}
				if (isBrand) {
					Con2 = "distance";
				}
			}
			if (b.getString(CON1VALUE) != null) {
				Con1Value = b.getString(CON1VALUE);
			}

		}

	}

	@Override
	public void setOnClick() {
		ls_card.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				CardDetailFragment cardInfoFragment = new CardDetailFragment();
				Bundle b = new Bundle();
				b.putString("CinfoID", list.get(position).getCinfoID());
				cardInfoFragment.setArguments(b);
				getFragmentManager().beginTransaction()
						.replace(R.id.fragment, cardInfoFragment)
						.addToBackStack(null).commit();

			}
		});
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(getActivity() instanceof CardActivity){
					getActivity().finish();
				}else{
					getActivity().getSupportFragmentManager().popBackStack();
				}
			}
		});

	}

	@Override
	public void showLoading() {
		// TODO Auto-generated method stub

	}

	@Override
	public void showLoaded(HashMap<String, AbsModule> map) {
		dataLoadDialog.dismiss();
		if (map.containsKey("0")) {
			if (module.cardInfoList.size() == 0) {
				setList();
				default_im.setVisibility(View.VISIBLE);
			} else {
				default_im.setVisibility(View.GONE);
				setSpinner1();
				setSpinner2();
				setList();
			}
		} else {
			refresh(map);
		}

	}

	private void setList() {
		CardInfoAdapter adapter = new CardInfoAdapter();
		ls_card.setAdapter(adapter);
		ls_card.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if (position - 1 >= 0) {
					CardDetailFragment cardDetailFragment = new CardDetailFragment();
					Bundle b = new Bundle();
					b.putString("CinfoID", module.cardInfoList
							.get(position - 1).getCinfoID());
					cardDetailFragment.setArguments(b);
					getFragmentManager().beginTransaction()
							.replace(R.id.fragment, cardDetailFragment)
							.addToBackStack(null).commit();
				}

			}
		});
	}

	private void setSpinner1() {

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
				R.layout.card_info_item_text);

		for (int i = 0; i < module.banklist.size(); i++) {
			adapter.add(module.banklist.get(i).getBankName());
		}
		ListView listview = new ListView(getActivity());
		listview.setVerticalScrollBarEnabled(false);
		listview.setCacheColorHint(getResources().getColor(R.color.divide));
		listview.setFadingEdgeLength(0);
		listview.setAdapter(adapter);
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				popupWindow.dismiss();
				tv1PullDown.setImageResource(R.drawable.pull_down_pre);
				tv1.setText(module.banklist.get(position).getBankName());
				getCard(module.banklist.get(position).getID(), Con2);
			}
		});
		popupWindow = new PopupWindow(getActivity());
		popupWindow.setHeight(Rl - ll_height - rl_height);

		popupWindow.setWidth(IConstants.DisplayWidth / 2);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setFocusable(true);
		popupWindow.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.pop_bg));
		popupWindow.setContentView(listview);
		tv1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				popupWindow.showAsDropDown(card_ly1);
				tv1PullDown.setImageResource(R.drawable.pull_down);
			}
		});

	}

	private void setSpinner2() {
		final String[] conditions = { getString(R.string.card_near),
				getString(R.string.card_new), getString(R.string.card_discount) };

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
				R.layout.card_info_item_text);
		if (isShop) {
			for (int i = 1; i < conditions.length; i++) {
				adapter.add(conditions[i]);
			}
		} else {
			for (int i = 0; i < conditions.length; i++) {
				adapter.add(conditions[i]);
			}
		}

		final ListView listview = new ListView(getActivity());
		listview.setVerticalScrollBarEnabled(false);
		listview.setCacheColorHint(getResources().getColor(R.color.divide));
		listview.setFadingEdgeLength(0);
		listview.setAdapter(adapter);
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> view, View arg1,
					int position, long arg3) {
				popupWindow2.dismiss();
				tv2PullDown.setImageResource(R.drawable.pull_down_pre);
				if (isShop) {
					getCard(BankID, con2s[position + 1]);
					tv2.setText(conditions[position + 1]);
				} else {
					tv2.setText(conditions[position]);
					getCard(BankID, con2s[position]);
				}

			}
		});

		popupWindow2 = new PopupWindow(getActivity());
		if (isShop) {
			popupWindow2.setHeight((4 * ll_height / 3));
		} else {
			popupWindow2.setHeight(2 * ll_height);
		}
		popupWindow2.setWidth(IConstants.DisplayWidth / 2);
		popupWindow2.setOutsideTouchable(true);
		popupWindow2.setFocusable(true);
		popupWindow2.setContentView(listview);
		popupWindow2.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.pop_bg));

		tv2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				popupWindow2.showAsDropDown(tv2);
				tv2PullDown.setImageResource(R.drawable.pull_down);
			}
		});

	}

	@Override
	public void showClick(HashMap<String, AbsModule> map) {
		// TODO Auto-generated method stub

	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> map) {
		// TODO Auto-generated method stub

	}

	public class CardInfoAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return module.cardInfoList.size() + 1;
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub

			return module.cardInfoList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int position, View view, ViewGroup arg2) {
			if (position == 0) {
				ImageView im = (ImageView) LayoutInflater.from(getActivity())
						.inflate(R.layout.card_title_im, null);

				// im.setOnClickListener(new OnClickListener() {
				//
				// @Override
				// public void onClick(View arg0) {
				// Intent intent = new Intent(getActivity(),
				// BhgActivity.class);
				// startActivity(intent);
				//
				// }
				// });
				im.setTag("0");
				return im;
			}
			ViewHodler viewHodler = null;

			if (position > 0) {
				if (view.getTag().equals("0")) {
					viewHodler = new ViewHodler();
					view = LayoutInflater.from(getActivity()).inflate(
							R.layout.card_info_item, null);
					viewHodler.name = (TextView) view
							.findViewById(R.id.card_info_item_shop_name);
					viewHodler.discount = (TextView) view
							.findViewById(R.id.card_info_item_discount);
					viewHodler.image = (ImageView) view
							.findViewById(R.id.card_item_image);
					viewHodler.bank_name = (TextView) view
							.findViewById(R.id.card_info_item_bank_name);
					viewHodler.distance = (TextView) view
							.findViewById(R.id.card_info_item_distandce);
					view.setTag(viewHodler);
				} else {
					viewHodler = (ViewHodler) view.getTag();
				}
			}
			viewHodler.name.setText(module.cardInfoList.get(position - 1)
					.getShopName());
			viewHodler.bank_name.setText(module.cardInfoList.get(position - 1)
					.getBankName());
			viewHodler.distance.setText(module.cardInfoList.get(position - 1)
					.getDistance());
			viewHodler.discount.setText(module.cardInfoList.get(position - 1)
					.getDiscount());
			imageLoader.displayImage(module.cardInfoList.get(position - 1)
					.getLogo(), viewHodler.image, options);

			if (module.cardInfoList.get(position - 1).getDistance() != null) {
				String distance1 = module.cardInfoList.get(position - 1)
						.getDistance();
				double dis;
				try {
					dis = Double.parseDouble(distance1) / 1000;
				} catch (Exception e) {
					dis = 0;
				}

				if (dis > 1) {
					DecimalFormat df = new DecimalFormat("#.0");
					String format = df.format(dis);
					viewHodler.distance.setText(format
							+ getResources().getString(R.string.kilometer));
				} else if (dis > 0 && dis < 1) {
					viewHodler.distance.setText(distance1
							+ getResources().getString(R.string.meter));
				} else if (dis <= 0) {
					viewHodler.distance.setText(getResources().getString(
							R.string.unknown));
				}

			}
			return view;
		}

		class ViewHodler {
			TextView name, bank_name, discount, distance;
			ImageView image;

		}
	}

}
